package com.hywood.live.pusher.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hywood.live.pusher.R;
import com.hywood.live.pusher.utils.FetchUtils;
import com.hywood.live.pusher.utils.ProperTies;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ScheduledThreadPoolExecutor;


public class MainActivity extends Activity {

    public static final String AUTHED_URL = "authed_url";
    public static final String LOGIN_BUNDLE = "login_bundle";
    public static final String CHANNEL_ID = "channel_id";
    public static final String CHANNEL_PASSWORD = "channel_password";
    public static final String GUID = "guid";
    public static final String LOGIN_RESULT = "login_result";
    private Button mButtonEnter;
    private TextView mChannelID;
    private TextView mChannelPassword;
    private String channalID;
    private String channalPassword;
    private ScheduledThreadPoolExecutor mExecutorService;
    private Context mContext;
    private InputMethodManager imm ;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        if (!permissionCheck()) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions(this, permissionManifest, PERMISSION_REQUEST_CODE);
            } else {
                showNoPermissionTip(getString(noPermissionTip[mNoPermissionIndex]));
                finish();
            }
        }
    }

    private void initView() {
        setContentView(R.layout.activity_main);
        mButtonEnter = findViewById(R.id.button_enter);
        mChannelID = findViewById(R.id.channel_id_input);
        mChannelPassword = findViewById(R.id.channel_password_input);
        this.mContext = this.getBaseContext();
        mButtonEnter.setOnClickListener(enterListener);
        imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (mExecutorService == null || mExecutorService.isShutdown()) {
            mExecutorService = new ScheduledThreadPoolExecutor(1,
                    new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
        }
    }

    private final View.OnClickListener enterListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            imm.hideSoftInputFromWindow(view.getWindowToken(),0);
            mButtonEnter.requestFocus();
            mButtonEnter.setClickable(false);
            if (mChannelID.getText().length() == 0 || mChannelPassword.getText().length() == 0) {
                Toast.makeText(MainActivity.this, R.string.empty_id_password, Toast.LENGTH_LONG).show();
                mButtonEnter.setClickable(true);
                return;
            }
            channalID = mChannelID.getText().toString();
            channalPassword = MainActivity.getMD5(mChannelPassword.getText().toString());

            mExecutorService.execute(new Runnable() {

                @Override
                public void run() {
                    String serviceUrl = ProperTies.getProperties(getApplicationContext()).getProperty("service.url");
                    String result = FetchUtils.getPusherUrl(serviceUrl ,channalID ,channalPassword);
                    if (result==null){
                        mButtonEnter.setClickable(true);
                        showToast(getString(R.string.ssdk_sms_dialog_net_error));
                        return;
                    }
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    if (!jsonObject.get("status").getAsString().equals("0")) {
                        showToast(jsonObject.get("msg").getAsString());
                        mButtonEnter.setClickable(true);
                        return;
                    }
                    String authedUrl = jsonObject.get("data").getAsJsonObject().get("pushUrl").getAsString();
                    Intent intent = new Intent(mContext, PushConfigActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString(CHANNEL_ID, channalID);
                    bundle.putString(CHANNEL_PASSWORD, channalPassword);
                    bundle.putString(GUID,jsonObject.get("data").getAsJsonObject().get("liveGuid").getAsString());
                    bundle.putString(LOGIN_RESULT,result);
                    intent.putExtra(LOGIN_BUNDLE,bundle);
                    intent.putExtra(AUTHED_URL,authedUrl);
                    startActivityForResult(intent,1);
                }
            });


        }
    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
            mChannelID.setText("");
            mChannelPassword.setText("");
            mButtonEnter.setClickable(true);
    }

    private int mNoPermissionIndex = 0;
    private final int PERMISSION_REQUEST_CODE = 1;
    private final String[] permissionManifest = {
            Manifest.permission.CAMERA,
            Manifest.permission.BLUETOOTH,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    private final int[] noPermissionTip = {
            R.string.no_camera_permission,
            R.string.no_record_bluetooth_permission,
            R.string.no_record_audio_permission,
            R.string.no_read_phone_state_permission,
            R.string.no_write_external_storage_permission,
            R.string.no_read_external_storage_permission,
    };

    private boolean permissionCheck() {
        int permissionCheck = PackageManager.PERMISSION_GRANTED;
        String permission;
        for (int i = 0; i < permissionManifest.length; i++) {
            permission = permissionManifest[i];
            mNoPermissionIndex = i;
            if (PermissionChecker.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionCheck = PackageManager.PERMISSION_DENIED;
            }
        }
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            return false;
        } else {
            return true;
        }
    }

    private void showNoPermissionTip(String tip) {
        Toast.makeText(this, tip, Toast.LENGTH_LONG).show();
    }
    private void showToast(final String text) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, text, Toast.LENGTH_LONG).show();
            }
        });
    }
    private static String getMD5(String string) {

        byte[] hash;

        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }

        return hex.toString();
    }
}
